import SqliteHelper from "@/sqlite/SqliteHelper";
import type { ScheduleType } from "@/typings/businessType";
import type { DatabaseParams } from "react-native-sqlite-storage";
import type { TableFieldsOption } from "@anlib/sqlite-orm/lib/types";

// 排期数据
const databaseParams: DatabaseParams = {
  name: "schedule.db",
  location: "default"
};

// 本地保存的字段数据, 具体类型见下面定义
const fields: TableFieldsOption[] = [
  { field: "id", type: "INTEGER", isKey: true },

  // 数据原始id
  { field: "sourceId", type: "VARCHAR" },
  { field: "createUser", type: "VARCHAR" },
  { field: "createUserName", type: "VARCHAR" },
  { field: "officeName", type: "VARCHAR" },
  { field: "officeCode", type: "VARCHAR" },
  { field: "name", type: "VARCHAR" },
  { field: "startDate", type: "VARCHAR" },
  { field: "endDate", type: "VARCHAR" },
  { field: "startTime", type: "VARCHAR" },
  { field: "code", type: "VARCHAR" },
  { field: "playFrequency", type: "VARCHAR" },
  { field: "playWeeks", type: "VARCHAR" }
];

// 初始化 sqlite
let sqlh: SqliteHelper | null = null;
const initSqlite = (): Promise<SqliteHelper> => {
  return new Promise((resolve, reject) => {
    const instance = new SqliteHelper(databaseParams, fields, 1);

    // 初始化
    instance
      .init()
      .then(res => {
        if (res instanceof SqliteHelper) {
          sqlh = res;
          resolve(sqlh);
        } else {
          reject(res);
        }
      })
      .catch(err => {
        reject(err);
      });
  });
};

// 关闭数据库
const closeSqlite = () => {
  if (sqlh) {
    sqlh.close();
    sqlh = null;
  }
};

// 定义sqling 数据的 ts 类型
type ScheduleSqliteType = ScheduleType & {
  /** 数据原始id */
  sourceId: string;
};

export { sqlh, initSqlite, closeSqlite, type ScheduleSqliteType };
